<template>
  <div>
    <el-container>
      <PublicHeader :menus="menus" :nav-width="'399px'" :active-text-color="'#4285F4'"
                    style="box-shadow: 0 1px 10px 0 #dfdfdf;">
        <template slot="left">
          <img src="/static/logo/logo_blue.png" alt="logo" width="128px">
        </template>
        <template slot="right">
          <HeaderRight></HeaderRight>
        </template>
      </PublicHeader>
      <el-main>
        <div class="view-home-box">
          <div class="view-home">
            <div class="home-content">
              <div class="header-common-border">
                <div class="top-handler">
                  <h2 class="left"></h2>
                  <div class="right">
                    <el-dropdown trigger="click" v-if="usertype ===0">
                      <span class="el-dropdown-link">
                        <el-button type="primary">+ 创建/加入课程</el-button>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item style="display: block">
                          <div @click="createCourseVisible = true">创建课程</div>
                        </el-dropdown-item>
                        <el-dropdown-item style="display: block">
                          <div @click="joinCourseVisible = true">加入课程</div>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <el-button type="primary" v-else @click="joinCourseVisible = true">+ 加入课程</el-button>
                    <el-dialog title="加入课程" :visible.sync="joinCourseVisible" style="text-align: left">
                      <el-form :model="joinCourseForm" :rules="joinCourseFormRules" ref="joinCourseForm">
                        <el-form-item label="加课码" prop="courseCode" label-width="80px">
                          <el-input v-model="joinCourseForm.courseCode" autocomplete="off"></el-input>
                        </el-form-item>
                      </el-form>
                      <div slot="footer" class="dialog-footer">
                        <el-button @click="resetJoinCourse('joinCourseForm')">取 消</el-button>
                        <el-button type="primary" @click="submitJoinCourse('joinCourseForm')">确 定</el-button>
                      </div>
                    </el-dialog>
                  </div>
                </div>
              </div>
              <div class="other-header">
                <div class="right">
                  <el-tabs v-model="myCourseType" @tab-click="getCoursesByType">
                    <el-tab-pane label="我教的" name="myTeach" style="font-size: 18px" v-if="usertype === 0">
                    </el-tab-pane>
                    <el-tab-pane label="我学的" name="myLearn">
                    </el-tab-pane>
                  </el-tabs>
                </div>
                <div class="left">
                  <el-button>归档管理</el-button>
                  <el-input v-model="search" placeholder="搜索我教的课程" autocomplete="off" clearable
                            style="margin-left: 24px" suffix-icon="el-icon-search"></el-input>
                </div>
              </div>

              <CourseSort
                :courses="courseSortValue"
                :sort-card-visible="sortCardVisible"
                @close="closeSortCard"
                @function="doFunction"></CourseSort>

              <div class="class-chapter common-border" v-for="(course, key, index) in courses" :key="index">
                <div class="class-handle">
                  <h3 class="left" style="cursor: pointer;"> {{ schoolYear[index] }} 第{{
                      term[index] === "1" ? '一' : '二'
                    }}学期 </h3>
                  <div class="right">
                    <el-button type="text" @click="showSortCard(course)">
                      <i class="el-icon-rank"></i>
                      课堂排序
                    </el-button>
                    <el-button type="text">
                      <i class="el-icon-caret-top"></i>
                      收起
                    </el-button>
                    <el-button type="text" style="display: none">
                      <i class="el-icon-caret-bottom"></i>
                      展开
                    </el-button>
                  </div>
                </div>
                <div class="class-box">
                  <span v-for="(cour, courIndex) in course" :key="courIndex">
                    <course-card
                      :course="cour"
                      :show-type="myCourseType === 'myTeach' ? 0 : 1"
                      @function="doFunction"></course-card>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
      <el-footer></el-footer>
    </el-container>

    <el-dialog
      title="创建课程"
      :visible.sync="createCourseVisible"
      width="70%"
      style="text-align: left">
      <span>
        <el-tabs v-model="infoType" @tab-click="">
          <el-tab-pane label="基本信息（必填）" name="first">
            <el-form :model="createCourse" :rules="rules" ref="createCourse" label-width="120px" class="demo-ruleForm">
              <el-form-item label="课程名称" prop="courseName">
                <el-input
                  v-model="createCourse.courseName"
                  maxlength="30"
                  show-word-limit></el-input>
              </el-form-item>
              <el-form-item label="教学班级" prop="clazz">
                <el-input
                  v-model="createCourse.clazz"
                  maxlength="20"
                  show-word-limit></el-input>
              </el-form-item>
              <el-form-item label="选择学年" prop="schoolYear">
                <el-select v-model="createCourse.schoolYear" placeholder="请选择学年">
                  <el-option
                    v-for="item in schoolYearOptions"
                    :key="item.schoolYear"
                    :label="item.schoolYear"
                    :value="item.schoolYear"
                    style="display: block">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="请选择学期" prop="term">
                <el-select v-model="createCourse.term" placeholder="请选择学期">
                  <el-option
                    v-for="item in courseTermOptions"
                    :key="item.term"
                    :label="item.term"
                    :value="item.value"
                    style="display: block">
                  </el-option>
                </el-select>
              </el-form-item>
              <span class="senior-set" @click="moreInfoVisible = !moreInfoVisible">
                更多信息
                <i class="el-icon-arrow-down" :style="{display: moreInfoVisible ? 'none' : 'inline-block'}"></i>
                <i class="el-icon-arrow-up" :style="{display: moreInfoVisible ? 'inline-block' : 'none'}"></i>
              </span>
              <div v-if="moreInfoVisible" class="none-view">
                <div class="line-desc">
                  <div class="TeachingRadio">
                    <span>授课模式</span>
                    <p>
                      <el-radio-group v-model="createCourse.model">
                        <el-radio :label="0">线上</el-radio>
                        <el-radio :label="1">线下</el-radio>
                        <el-radio :label="2">混合</el-radio>
                      </el-radio-group>
                    </p>
                  </div>
                  <div class="TeachingTimer">
                    <span>学时数</span>
                      <div class="TeachingTimer-select">
                        <div class="TeachingTimer-input">
                          <input type="number" min="0" placeholder="请输入学时" v-model="createCourse.period">
                        </div>
                      </div>
                  </div>
                </div>
                <div class="courseIntro">
                  <h2 class="mb12">课程介绍</h2>
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入内容"
                    v-model="createCourse.details">
                  </el-input>
                </div>
                <div class="classAddress">
                  <label class="flex-align">
                    <span>授课地点</span>
                    <el-input style="flex: 1 1 0%" v-model="createCourse.place"></el-input>
                  </label>
                </div>
              </div>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="高级设置" name="second">高级设置</el-tab-pane>
        </el-tabs>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetCreateCourseForm('createCourse')">取 消</el-button>
        <el-button type="primary" @click="submitCreateCourse('createCourse')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PublicHeader from "../../components/PublicHeader";
import HeaderRight from "../../components/HeaderRight";
import CourseCard from "../../components/CourseCard";
import {mymessage} from "../../tools/mymessage";
import CourseSort from "../../components/CourseSort";

export default {
  name: "Main",
  components: {CourseSort, CourseCard, HeaderRight, PublicHeader},
  data() {
    return {
      menus: [
        {
          name: '我的课堂',
          route: '/courseList'
        },
        {
          name: '备课区',
          route: '/lessonPreparation'
        },
        {
          name: '论文管理',
          route: '/thesisDefense'
        }
      ],
      myCourseType: 'myTeach',
      usertype: this.$store.getters.userInfo.usertype,
      search: '',
      courses: {
      },
      schoolYear: [],
      term: [],
      createCourseVisible: false,
      infoType: 'first',
      createCourse: {
        courseName: "",
        clazz: "",
        schoolYear: "",
        term: '',
        place: '',
        details: "",
        model: '',
        period: '',
        sort: 0
      },
      schoolYearOptions: [
        {
          schoolYear: '2022-2023'
        },
        {
          schoolYear: '2021-2022'
        },
        {
          schoolYear: '2020-2021'
        },
        {
          schoolYear: '2019-2020'
        },
        {
          schoolYear: '2018-2019'
        },
        {
          schoolYear: '2017-2018'
        }
      ],
      courseTermOptions: [
        {
          term: '第一学期',
          value: 1
        },
        {
          term: '第二学期',
          value: 2
        }
      ],
      moreInfoVisible: false,
      rules: {
        courseName: [
          {required: true, message: '必填项', trigger: 'blur'}
        ],
        clazz: [
          {required: true, message: '必填项', trigger: 'blur'}
        ],
        schoolYear: [
          {required: true, message: '必填项', trigger: 'blur'}
        ],
        term: [
          {required: true, message: '必填项', trigger: 'blur'}
        ]
      },
      joinCourseVisible: false,
      joinCourseForm: {
        courseCode: '',
        userId: -1
      },
      joinCourseFormRules: {
        courseCode: [
          {required: true, message: '必填项', trigger: 'blur'}
        ]
      },
      sortCardVisible: false,
      courseSortValue: []
    }
  },
  methods: {
    getOnePageCoursesByType(type) {
      let id = this.$store.getters.userInfo.id;

      if (type === 0) {
        this.myCourseType = 'myTeach'
      } else
        this.myCourseType = 'myLearn'

      this.getRequest('/course/main/' + id + '/' + type).then(resp => {
        if (resp.code === 200) {
          this.courses = resp.data;
          console.log("this.courses", this.courses);
          this.schoolYear = Object.keys(this.courses)

          this.schoolYear.forEach((year, index) => {
            this.term[index] = year.substring(10, 11)
          })
          this.schoolYear.forEach((year, index) => {
            this.schoolYear[index] = year.substring(0, 9)
          })
        }
      })
    },
    doFunction(data) {
      if (data === 'delete') {
        this.getOnePageCoursesByType(0)
      } else if (data === 'edit') {
        this.getOnePageCoursesByType(0)
      } else if (data === 'quit') {
        this.getOnePageCoursesByType(1)
      } else if (data === 'sort') {
        this.sortCardVisible = false
        let usertype = this.$store.getters.userInfo.usertype
        location.reload()
        this.getOnePageCoursesByType(usertype)
      }
    },
    submitCreateCourse(createCourseForm) {
      this.$refs[createCourseForm].validate(valid => {
        if (valid) {
          var userId = this.$store.getters.userInfo.id
          this.createCourse.period = Number(this.createCourse.period)
          if (this.createCourse.period === 0) {
            this.createCourse.period = 48
          }

          var schoolYearAndTerm = this.createCourse.schoolYear + '-' + this.createCourse.term
          if (this.courses[schoolYearAndTerm] === undefined) {
            this.createCourse.sort = 0
          } else {
            this.createCourse.sort = this.courses[schoolYearAndTerm].length // 从课程中得出某学年某学期的课程数
          }
          this.postRequest('/course/insert/' + userId + '/' + this.createCourse.sort, this.createCourse).then(resp => {
            console.log("resp", resp);
            if (resp.code === 200) {
              this.resetCreateCourseForm(createCourseForm)
              mymessage.success("创建课程成功")
              this.getOnePageCoursesByType(0)
            } else {
              mymessage.error("创建课程失败")
            }
          })
        } else {
          return false
        }
      })
    },
    resetCreateCourseForm(createCourseForm) {
      this.createCourseVisible = false
      this.$refs[createCourseForm].resetFields();
    },
    getCoursesByType(tab, event) {
      if (tab.name === 'myTeach') {
        this.getOnePageCoursesByType(0)
      } else {
        this.getOnePageCoursesByType(1)
      }
    },
    submitJoinCourse(joinCourseForm) {
      this.$refs[joinCourseForm].validate(valid => {
        if (valid) {
          this.joinCourseForm.userId = this.$store.getters.userInfo.id
          this.putRequest('/course/add/' + this.joinCourseForm.courseCode + '/' + this.joinCourseForm.userId + '/' + 0).then(resp => {
            console.log("resp", resp);
            if (resp.code === 200) {
              this.joinCourseVisible = false
              this.getOnePageCoursesByType(1)
              mymessage.success("加入课程成功")
              this.resetJoinCourse(joinCourseForm)
            }else {
              mymessage.error("加入课程失败");
            }
          })
        }
      })
    },
    resetJoinCourse(joinCourseForm) {
      this.joinCourseVisible = false
      this.$refs[joinCourseForm].resetFields()
    },
    showSortCard(course) {
      this.courseSortValue = course
      this.sortCardVisible = true
    },
    closeSortCard(value) {
      this.sortCardVisible = value
    },
    /*    dataDragEnd(evt) {
          evt.preventDefault();
          console.log('拖动前的索引 :', evt.oldIndex)
          console.log('拖动后的索引 :', evt.newIndex)
          for (let i = 0; i < this.courses.length; i++) {
            this.courses[i].rank = i;
          }
          console.log(this.courses)
          // this.$emit("updateCourseRank",this.courses)
        },*/
  },
  created() {
    // this.$store.commit('REMOVE_CURRENT_COURSE_ID')
    var usertype = this.$store.getters.userInfo.usertype
    this.getOnePageCoursesByType(usertype);
  }
}
</script>

<style scoped>
.view-home-box {
  max-width: 1150px;
  margin: 0 auto;
}

.view-home {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.view-home .home-content {
  flex: 1;
}

.view-home .header-common-border {
  border-radius: 8px;
  padding-top: 18px;
  padding-bottom: 8px;
}

.view-home .top-handler {
  display: flex;
  justify-content: space-between;
}

.view-home .top-handler .left {
  font-size: 20px;
  font-family: PingFangSC, PingFangSC-Medium;
  color: #575a5b;
  font-weight: 500;
}

.view-home .top-handler .right {
  display: flex;
  align-items: center;
  font-size: 12px;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  color: #4285f4;
}

.view-home .home-content .other-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  padding-bottom: 12px;
  font-size: 20px;
  color: #575a5b;
  line-height: 24px;
}

.view-home .home-content .other-header {
  padding-top: 12px;
  padding-bottom: 12px;
  font-size: 20px;
  color: #575a5b;
  line-height: 24px;
}

.view-home .home-content .other-header .left {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.view-home .el-button {
  padding: 10px 20px;
  margin-left: 12px;
}

.view-home .common-border {
  border: 1px solid #dadce0;
  border-radius: 8px;
  padding: 18px;
}

.view-home .home-content .class-chapter {
  background: #f8f9fa;
  margin-bottom: 24px;
}

.view-home .home-content .class-chapter .class-handle {
  display: flex;
  flex-flow: nowrap;
  justify-content: space-between;
}

.view-home .home-content .class-chapter .class-handle .right {
  display: flex;
}

.view-home .home-content .class-box {
  margin: 8px -10px 0;
  display: flex;
  flex-flow: row wrap;
  overflow-y: auto;
}

.senior-set {
  color: #2092e6;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 15px;
  display: block;
}

.none-view {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 15px;
}

.none-view .line-desc {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.TeachingRadio {
  display: flex;
  align-items: center;
  margin-right: 50px;
  color: #3c4043;
  font-size: 14px;
}

.TeachingRadio > span {
  margin-right: 15px;
}

.TeachingTimer {
  display: flex;
  align-items: center;
}

.TeachingTimer > span {
  color: #3c4043;
  font-size: 14px;
  margin-right: 8px;
}

.TeachingTimer .TeachingTimer-select {
  position: relative;
}

.TeachingTimer .TeachingTimer-select .TeachingTimer-input {
  width: 110px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dadce0;
  border-radius: 4px;
  background: #fff;
}

.TeachingTimer .TeachingTimer-select .TeachingTimer-input input {
  width: 100px;
  outline: none;
  color: #afb1b3;
  font-size: 12px;
}

.mb12 {
  margin-bottom: 12px;
}

.classAddress {
  margin-top: 18px;
}

.flex-align {
  display: flex;
  align-items: center;
}

.classAddress span {
  margin-right: 20px;
}
</style>
